import { BulletDirection, PlaneCamp } from "../Constant/Constant";
import PoolManager from "../Manager/PoolManager";
import BulletControl from "./BulletControl";

const { ccclass, property } = cc._decorator;

@ccclass
export default class EnemyBulletControl extends cc.Component {

  @property(cc.Prefab)
  bulletPrefab: cc.Prefab = null

  @property
  bulletSpeed: number = 300

  @property
  bulletInterval: number = 0.5

  @property
  bulletRepeat: number = 1

  private bulletCount: number = 0

  private intervalId: number = null


  start() {
    // this.createBullet() // 出现时发射一颗子弹
    this.intervalId = setInterval(this.createBullet.bind(this), 1000 * this.bulletInterval)
  }

  unuse() {
    // console.log('unuse')
    clearInterval(this.intervalId)
  }

  reuse() {
    // console.log('reuse')
    this.intervalId = setInterval(this.createBullet.bind(this), 1000 * this.bulletInterval)
  }

  /**
   * 创建子弹
   */
  private createBullet(): void {
    const bullet = PoolManager.instance.getNode(this.bulletPrefab)
    const bulletControl = bullet.getComponent(BulletControl)
    // 配置子弹速度、发射对象、发射方向
    if (bulletControl != null) {
      bulletControl.speed = this.bulletSpeed
      bulletControl.from = PlaneCamp.ENEMY
      bulletControl.direction = BulletDirection.DOWN
    }
    bullet.parent = this.node.parent
    bullet.setPosition(this.node.x, this.node.y - (this.node.height * this.node.scaleY / 2) - 10)

    // 关闭定时器
    this.bulletCount++
    if (this.bulletCount >= this.bulletRepeat) {
      clearInterval(this.intervalId)
    }
  }

  onDestroy(): void {
    clearInterval(this.intervalId)
  }
}
